import os

from flask import g, render_template, redirect, abort, request, jsonify, current_app

from . import user_blue
from info.common import user_login_data
from ...constants import USER_COLLECTION_MAX_NEWS
from ...models import tb_user_collection, Category, News
from ...response_code import RET, error_map
import datetime
from datetime import date
from ... import db


# 1.用户首页
@user_blue.route("/info")
@user_login_data
def user_info():
    user = g.user
    if not user:
        return redirect("/")
    return render_template("news/user.html", data={"user": user.to_dict()})


# 2.用户基本信息展示
@user_blue.route("/base_info", methods=["POST", "GET"])
@user_login_data
def base_info():
    user = g.user
    if not user:
        return abort(403)
    # GET处理
    if request.method == "GET":
        return render_template("news/user_base_info.html", data={"user": user.to_dict()})
    # POST处理
    signature = request.json.get("signature")
    nick_name = request.json.get("nick_name")
    gender = request.json.get("gender")

    if not all([signature, nick_name, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    if gender not in ["WOMAN", "MAN"]:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    user.signature = signature
    user.nick_name = nick_name
    user.gender = gender
    return jsonify(errno=RET.OK, error_map=error_map[RET.OK])


# 3.用户头像的修改
@user_blue.route("/pic_info", methods=["POST", "GET"])
@user_login_data
def pic_info():
    user = g.user
    if not user:
        return abort(403)
    # GET获取头像处理
    if request.method == "GET":
        return render_template("news/user_pic_info.html", user=user.to_dict())

    # POST修改头像处理
    try:
        image = request.files.get("avatar")
        if not image:
            return jsonify(errno=RET.PARAMERR, errmsg="未传入头像")
        image_bytes = image.read()
        try:
            local_filename = os.path.join(current_app.static_folder, 'picture', user.mobile + ".jpg")
            with open(local_filename, 'wb') as f:
                f.write(image_bytes)
            user.avatar_url = 'picture/'+user.mobile + ".jpg"
        except BaseException as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg="修改头像出错")
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsy=error_map[RET.PARAMERR])
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK],data=user.to_dict())


# 4.我的关注
@user_blue.route("/user_follow")
@user_login_data
def user_follow():
    user = g.user
    if not user:
        return abort(403)
    p = request.args.get("p", 1)

    try:
        p = int(p)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg=error_map[RET.PARAMERR])
    author_list = []
    cur_page = 1
    total_page = 1
    try: # page=cur_page,per_page=per_count
        pn = user.followed.paginate(page= p,per_page=USER_COLLECTION_MAX_NEWS)
        author_list = [author.to_dict() for author in pn.items]
        cur_page = pn.page
        total_page = pn.pages
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    data = {
        "author_list": author_list,
        "cur_page": cur_page,
        "total_page": total_page
    }

    return render_template("news/user_follow.html", data=data)


# 5.密码修改
@user_blue.route("/pass_info", methods=["POST", "GET"])
@user_login_data
def pass_info():
    user = g.user
    if not user:
        return abort(403)
    if request.method == "GET":
        return render_template("news/user_pass_info.html")

    # post修改密码
    old_password = request.json.get("old_password")
    new_password = request.json.get("new_password")
    if not all([old_password,new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
    if not user.check_password(old_password):
        return jsonify(errno=RET.PARAMERR,errmsg = "密码错误")
    user.password = new_password
    return jsonify(errno=RET.OK,error_map=error_map[RET.OK])


# 6.收藏新闻展示
@user_blue.route("/collection")
@user_login_data
def user_collection():
    user = g.user
    if not user:
        return abort(403)
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg=error_map[RET.PARAMERR])
    news_list = []
    cur_page = 1
    total_page = 1
    try:
        pn = user.collection_news.order_by(tb_user_collection.c.create_time.desc())\
            .paginate(page= p,per_page=USER_COLLECTION_MAX_NEWS)

        news_list = [news.to_dict() for news in pn.items]
        cur_page = pn.page
        total_page = pn.pages
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg=error_map[RET.DBERR])
    data = {
        "news_list": news_list,
        "cur_page": cur_page,
        "total_page": total_page
    }
    return render_template("news/user_collection.html", data=data)


# 7.用户的新闻发布用户与新闻的关系
@user_blue.route("/news_release",methods=["POST","GET"])
@user_login_data
def user_release():
    user = g.user
    if not user:
        return abort(403)
    if request.method == "GET":
        categories = []
        try:
            categories = Category.query.all()
        except BaseException as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg=error_map[RET.DBERR])

        if len(categories):
            categories.pop(0)
        return render_template("news/user_news_release.html",categories=categories)

    title = request.form.get("title")
    category_id = request.form.get("category_id")
    digest = request.form.get("digest")
    content = request.form.get("content")
    if not all([title,category_id,digest,content]):
        return jsonify(errno=RET.PARAMERR,errmsg=error_map[RET.PARAMERR])
    try:
        category_id = int(category_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg=error_map[RET.PARAMERR])
    news = News()
    news.title = title
    news.category_id = category_id
    news.digest = digest
    news.content = content
    news.user_id = user.id
    news.status = 1 # 设置审核状态
    news.source = "个人发布"

    # POST修改头像处理
    try:
        image = request.files.get("index_image")
        if not image:
            return jsonify(errno=RET.PARAMERR,errmsg=error_map[RET.PARAMERR])
        image_bytes = image.read()
        try:
            local_filename = os.path.join(current_app.static_folder, 'picture', date.strftime(datetime.datetime.now() ,"%d:%m:%Y:%H:%M:%S") + ".jpg")
            with open(local_filename, 'wb') as f:
                f.write(image_bytes)
            news.index_image_url = 'picture/' + date.strftime(datetime.datetime.now() ,"%d:%m:%Y:%H:%M:%S") + ".jpg"
        except BaseException as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg="写入图片出错")
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsy=error_map[RET.PARAMERR])

    # 添加到数据库
    db.session.add(news)

    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])


# 8.用户的新闻列表
@user_blue.route("/news_list", methods=["GET"])
@user_login_data
def news_list():
    user = g.user
    if not user:
        return abort(403)
    p = request.args.get("p",1)
    try:
        p = int(p)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
    news_list = []
    cur_page = 1
    total_page = 1
    try:
        pn = user.news_list.order_by(News.create_time.desc()).paginate(page=p, per_page=USER_COLLECTION_MAX_NEWS)
        news_list = [news.to_dict() for news in pn.items]
        cur_page = pn.page
        total_page = pn.page
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg=error_map[RET.DBERR])
    data = {
        "news_list": news_list,
        "cur_page": cur_page,
        "total_page": total_page
    }
    return render_template("news/user_news_list.html",data=data)




